<template>
  <div class="page-container">
    <!--表格内容栏-->
    <ac-table
      ref="dataTable" 
      pkName="id" 
      :filters="filters"
      :filterFields="filterFields" 
      :columns="columns" 
      :defaultSort="defaultSort"
      @handleTableOperator="handleTableOperator"
    ></ac-table>

    <!--新增编辑界面-->
    <el-dialog
      :title="operator"
      width="500px"
      v-model="dialogVisible"
      :close-on-click-modal="false"
      append-to-body
      destroy-on-close
      draggable
    >
      <el-form
        :model="formData"
        label-width="120px"
        :rules="rules"
        ref="dataForm"
        label-position="right"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="formData.name" auto-complete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          size="default"
          type="info"
          @click="dialogVisible = false"
        >取消</el-button>
        <el-button
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
      </template>
    </el-dialog>

    <el-dialog
      :title="operator"
      width="950px"
      v-model="dialogPoVisible"
      :close-on-click-modal="false"
      class="privilege-dialog full-height no-padding"
      destroy-on-close
      fullscreen
    >
      <div class="dialog-body">
        <div class="dialog-body-left">
          <div class="tip-title">菜单权限设置</div>
          <el-input
            placeholder="搜索"
            v-model="menuFilterText"
            style="margin-bottom: 10px"
            clearable
          />
          <el-tree
            ref="menuTree"
            :data="menuTreeData"
            :default-checked-keys="menuTreeChecked"
            :default-expanded-keys="menuTreeExpanded"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            default-expand-all
            show-checkbox
            node-key="id"
            check-strictly
            @check="menuCheckClick"
            @node-click="menuNodeClick"
          />
        </div>
        <div class="dialog-body-right">
          <div class="tip-title">页面权限设置</div>
          <el-input
            placeholder="搜索"
            v-model="pageFilterText"
            style="margin-bottom: 10px"
            clearable
          />
          <el-tree
            ref="pageTree"
            :data="pageTreeData"
            :default-checked-keys="pageTreeChecked"
            :props="treeProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            default-expand-all
            show-checkbox
            node-key="id"
            check-strictly
            @check="pageCheckClick"
            @node-click="pageNodeClick"
          />
        </div>
      </div>
      <template #footer>
        <el-button
          size="default"
          type="info"
          @click="dialogPoVisible = false"
        >取消</el-button>
        <el-button
          size="default"
          type="primary"
          @click="submitPoForm"
          :loading="editPoLoading"
        >提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/http/api';
import { useRoleStore } from "@/pinia/modules/role";
import tool from "@/utils/tool";

const filters = ref({ name: '' });
const filterFields = ref([
  {prop: "name", label: "角色名称"},
]);
const columns = ref([
  {prop: "name", label: "角色名称", minWidth: 200},
  {prop: "updateTime", label: "更新时间", width: 160, type: "datetime"},
  {prop: "createTime", label: "创建时间", width: 160, type: "datetime"},
]);
const operator = ref('');
const loading = ref(false);
const dialogVisible = ref(false);
const dialogPoVisible = ref(false);
const editLoading = ref(false);
const editPoLoading = ref(false);
const formPoData = ref({});
const formData = ref({
  id: '',
  name: '',
  power: '',
  button: {}
});
const rules = ref({
  name: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
});
const defaultSort = ref({prop: 'power', order: 'ascending'});
const dataForm = ref();
const dataTable = ref();
const roleStore = useRoleStore();

const menuTree = ref();
const menuFilterText = ref('');
const menuTreeData = ref([]);
const menuTreeChecked = ref([]);
const menuTreeExpanded = ref([]);

const pageTree = ref();
const pageFilterText = ref('');
const pageTreeData = ref([]);
const pageTreeChecked = ref([]);

const treeProps = ref({
  children: "children",
  label: (data) => {
    switch (data.type) {
      case 'subsystem':
        return data.text + '（系统）';
      case 'menu':
        return data.text + '（菜单）';
      case 'page':
        return data.text + '（页面）';
      case 'comp':
        return data.text + '（组件）';
      case 'button':
        return data.text + '（按钮）';
      default:
        return data.text
    }
  },
  class: (data) => {
    return data.type;
  }
});

const filterNode = (value, data, node) => {
  if (!value) return true;
  if (data.text) {
    return chooseNode(value, data, node);
  }
};

const chooseNode = (value, data, node) => {
  if (data.text.indexOf(value) !== -1) {
    return true
  }
  const level = node.level
  if (level === 1) {
    return false
  }
  let parentData = node.parent
  let index = 0
  while (index < level - 1) {
    if (parentData.data.text.indexOf(value) !== -1) {
      return true
    }
    parentData = parentData.parent
    index++
  }
  return false
};

const menuCheckClick = async(data, tree) => {
  if (tree.checkedKeys.indexOf(data.id) >= 0) {
    const parentId = findParentId(data.id, menuTreeData.value, []) || [];
    parentId.forEach(id => menuTree.value.setChecked(id, true, false));
  } else {
    checkedAll(menuTree.value, findNode(data.id, menuTreeData.value), false);
  }

  await nextTick(() => menuChange());
};

const menuNodeClick = (data, node) => {
  if (!node.checked && data.pid !== '0') {
    const parentId = findParentId(data.id, menuTreeData.value, []) || [];
    parentId.forEach(id => menuTree.value.setChecked(id, !node.checked, false));
  }

  checkedAll(menuTree.value, findNode(data.id, menuTreeData.value), !node.checked);
  nextTick(() => menuChange());
};

const menuChange = () => {
  tool.walkTree({children: menuTreeData.value}, node => {
    if (node.data.id && node.data.id.indexOf("@") > 0) {
      const ids = node.data.id.split("@");
      pageTree.value.setChecked(ids[ids.length - 1], false, false)
    } else {
      pageTree.value.setChecked(node.data.id, false, false);
    }
  });

  const privilegeIdSet = new Set();
  menuTree.value.getHalfCheckedNodes().forEach(node => {
    if (node.data.id && node.data.id.indexOf("@") > 0) {
      const ids = node.data.id.split("@");
      privilegeIdSet.add(ids[ids.length - 1]);
    } else {
      privilegeIdSet.add(node.data.id);
    }
  });
  menuTree.value.getCheckedNodes().forEach(node => {
    if (node.data.id && node.data.id.indexOf("@") > 0) {
      const ids = node.data.id.split("@");
      privilegeIdSet.add(ids[ids.length - 1]);
    } else {
      privilegeIdSet.add(node.data.id);
    }
  });

  privilegeIdSet.forEach(id => pageTree.value.setChecked(id, true, false));
};

const pageCheckClick = async(data, tree) => {
  if (tree.checkedKeys.indexOf(data.id) >= 0) {
    const parentId = findParentId(data.id, pageTreeData.value, []) || [];
    parentId.forEach(id => pageTree.value.setChecked(id, true, false));
  } else {
    checkedAll(pageTree.value, findNode(data.id, pageTreeData.value), false);
  }
};

const pageNodeClick = (data, node) => {
  if (!node.checked && data.pid !== '0') {
    const parentId = findParentId(data.id, pageTreeData.value, []) || [];
    parentId.forEach(id => pageTree.value.setChecked(id, !node.checked, false));
  }

  checkedAll(pageTree.value, findNode(data.id, pageTreeData.value), !node.checked);
};

const findNode = (id, list) => {
  if (!list) return null;

  for (let item of list) {
    if (item.id === id) {
      return item;
    }

    const node = findNode(id, item.children);
    if (node) {
      return node;
    }
  }

  return null;
};

const checkedAll = (ref, node, checked) => {
  if (!node) return;

  ref.setChecked(node.id, checked, false);
  for (let child of (node.children || [])) {
    checkedAll(ref, child, checked);
  }
};

const findParentId = (id, list, result) => {
  if (!list) return null;

  for (let item of list) {
    if (item.id === id) {
      return result;
    }

    const parentId = findParentId(id, item.children, result.concat(item.id));
    if (parentId) {
      return parentId;
    }
  }

  return null;
};

const handleTableOperator = (button, row) => {
  operator.value = button.name;
  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button})
  } else if (button.buttonType === 'editPo') {
    operator.value = button.name + '【' + row.name + '】';
    menuTreeData.value = [];
    menuTreeChecked.value = [];
    pageTreeData.value = [];
    pageTreeChecked.value = [];
    loading.value = true;
    dialogPoVisible.value = true;
    formPoData.value = Object.assign({}, row, {button: button})
    api.post(button.dataSourUrl, {id: row.id}).then(res => {
      menuTreeData.value = res.data.menuTree && res.data.menuTree.children || [];
      menuTreeExpanded.value = menuTreeData.value.map(item => item.id);
      pageTreeData.value = res.data.pageTree && res.data.pageTree.children || [];

      const privilegeIdSet = new Set();
      const rolePrivilege = res.data.rolePrivilege || [];
      rolePrivilege.forEach(item => {
        if (!item.menuId) {
          menuTreeChecked.value.push(item.privilegeId);
        }
        privilegeIdSet.add(item.privilegeId);
      });
      pageTreeChecked.value.push(...privilegeIdSet);

      tool.walkTree(res.data.menuTree || {}, node => {
        if (!node.data || !node.data.id || node.data.id.indexOf('@') < 0) return;

        const ids = node.data.id.split("@");
        rolePrivilege.forEach(item => {
          if (item.menuId && item.privilegeId && ids[0] === item.menuId && ids[ids.length - 1] === item.privilegeId) {
            menuTreeChecked.value.push(node.id);
          }
        });
      });
      nextTick(() => loading.value = false);
    }).catch(() => {
      loading.value = false
    });
    return;
  } else {
    formData.value = {
      id: '',
      name: '',
      power: '',
      button: button
    };
  }

  dialogVisible.value = true
  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const submitPoForm = () => {
  ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
    editPoLoading.value = true;
    const menuHalfChecked = menuTree.value.getHalfCheckedNodes().map(node => node.type + '--' + node.id);
    const pageHalfChecked = pageTree.value.getHalfCheckedNodes().map(node => node.type + '--' + node.id);
    const menuChecked = menuTree.value.getCheckedNodes().map(node => node.type + '--' + node.id);
    const pageChecked = pageTree.value.getCheckedNodes().map(node => node.type + '--' + node.id);
    const data = {
      id: formPoData.value.id,
      privilegeIds: menuHalfChecked.concat(pageHalfChecked).concat(menuChecked).concat(pageChecked)
    }
    api.post(formPoData.value.button.dataDestUrl, data).then(res => {
      ElMessage.success(res.message);
      dialogPoVisible.value = false;
      editPoLoading.value = false;
    }).catch(() => {
      editPoLoading.value = false;
    })
  }).catch(()=>{});
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true
        api.post(formData.value.button.dataDestUrl, formData.value).then((res) => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataTable.value.findPage()
          editLoading.value = false;
          roleStore.clearRole();
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(()=>{});
    }
  });
};

watch(() => menuFilterText.value, (val) => {
  menuTree.value.filter(val);
});

watch(() => pageFilterText.value, (val) => {
  pageTree.value.filter(val);
});
</script>

<style scoped>
.operator-dialog :deep(.el-table td .cell) {
  padding-left: 10px;
}
.operator-dialog :deep(.el-table td .el-checkbox-group) {
  white-space: normal;
}

.table-container :deep(.el-table) {
  height: calc(100vh - 240px)!important;
}
.table-container :deep(.tree-col) {
  height: calc(100vh - 240px)!important;
}
.dialog-body {
  display: flex;
  flex-direction: row;
  height: calc(100% - 30px);
  padding: 15px;
}
.dialog-body-left, .dialog-body-right {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.dialog-body-left {
  width: 45%;
  padding-right: 15px;
  border-right: 1px solid #dedfe1;
}
.dialog-body-right {
  flex-grow: 1;
  margin-left: 15px;
}
.dialog-body .el-tree {
  flex-grow: 1;
  overflow: auto;
}
.dialog-body .tip-title {
  margin-bottom: 10px;
  font-weight: 600;
  font-size: 16px;
}
.dialog-body :deep(.subsystem) > .el-tree-node__content,
.dialog-body :deep(.subsystem) > .el-tree-node__content .el-text {
  color: #ff4500
}
.dialog-body :deep(.menu) > .el-tree-node__content,
.dialog-body :deep(.menu) > .el-tree-node__content .el-text  {
  color: #1e90ff
}
.dialog-body :deep(.page) > .el-tree-node__content,
.dialog-body :deep(.page) > .el-tree-node__content .el-text  {
  color: #006E73;
}
.dialog-body :deep(.comp) > .el-tree-node__content,
.dialog-body :deep(.comp) > .el-tree-node__content .el-text  {
  color: #0AB061;
}
</style>